//
//  LogOnViewController.m
//  TenMinDemo
//
//  Created by Shawn Li on 2021/3/11.
//  Copyright © 2021 CYXiang. All rights reserved.
//

#import "LogOnViewController.h"
#import "RegistViewController.h"
#import "RetrievePswViewController.h"
#import "ForgetPswViewController.h"
#import "CYXBaseRequest.h"
#import "CheckInput.h"
#import "VerifyCodeBtn.h"
#import "LanguageSelectTableViewController.h"
#import "BaseTextField.h"
#import "PicVerCodeView.h"
#import "CountryCodeSelectViewController.h"

@interface LogOnViewController ()<UITextFieldDelegate>
//@property (weak, nonatomic) IBOutlet NSLayoutConstraint *bgTop;
@property (weak, nonatomic) IBOutlet UIScrollView *scrollBgView;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *scrollBgBottom;
@property (weak, nonatomic) IBOutlet BaseTextField *phoneInput;
@property (weak, nonatomic) IBOutlet BaseTextField *pswInput;
@property (weak, nonatomic) IBOutlet UILabel *errMsg;
@property (weak, nonatomic) IBOutlet BaseTextField *pvcInput;
@property (weak, nonatomic) IBOutlet UIButton *pvcBtn;
@property (weak, nonatomic) IBOutlet UILabel *pvcSepLine;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *errMsgTop; // 5 / 64
@property (weak, nonatomic) IBOutlet VerifyCodeBtn *verBtn;

@property (weak, nonatomic) IBOutlet UIButton *codeSelectBtn;

/// 是否需要图形验证码
@property (nonatomic, assign) BOOL needGvc;
/// 是否需要手机验证码
@property (nonatomic, assign) BOOL needPvc;

/// 国家码
@property (nonatomic, copy) NSString *countryCode;

@end

@implementation LogOnViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
}

- (void)setupUI{
    [super setupUI];
    self.view.backgroundColor = LRRGBColor(80, 42, 154);
    
    self.phoneInput.placeholder = LCLocalString(@"plh_qssjh");
    self.phoneInput.placeholderColor = PlhColor;
    self.pswInput.placeholder = LCLocalString(@"plh_qsrmm");
    self.pswInput.placeholderColor = PlhColor;
    self.pvcInput.placeholder = LCLocalString(@"plh_qsryzm");
    self.pvcInput.placeholderColor = PlhColor;
    
    [self setMainEditScrollScrollView:self.scrollBgView andScrollViewBottom:self.scrollBgBottom];
    LRWeakSelf(self);
    self.verBtn.clickBlock = ^{
//        [weakself getPvc_net];
        [weakself.view endEditing:YES];
        [weakself getGvc];
    };
    [self.verBtn configVerifyBtn:60];
    
    [self setLeftNavItem:nil font:nil color:nil icon:@"fh_w"];
}

- (void)getGvc{
    PicVerCodeView *view = [[PicVerCodeView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREENH_HEIGHT)];
    view.gvcApi = API_getGvc;
    LRWeakSelf(self);
    view.actionBlock = ^(NSInteger index,NSString *gvCode) {
        CYXLog(@"%zd",index);
        if(index == 1){
            [weakself.view endEditing:YES];
            [weakself getPvc_net:gvCode];
        }
    };
    
    [view showInView:self.navigationController.view];
}

- (void)leftNavItemClick:(id)sender{
    [self dismissViewControllerAnimated:YES completion:nil];
}
- (IBAction)regisAction:(id)sender {
    RegistViewController *vc = LoadVCFormXib(RegistViewController);
    [self.navigationController pushViewController:vc animated:YES];
}
- (IBAction)fogetPswAction:(id)sender {

//    RetrievePswViewController *vc = LoadVCFormXib(RetrievePswViewController);
//    [self.navigationController pushViewController:vc animated:YES];
    
    ForgetPswViewController *vc = LoadVCFormXib(ForgetPswViewController);
    [self.navigationController pushViewController:vc animated:YES];
    
}

- (IBAction)logOnAction:(id)sender {
    if(![self checkInput]) return;
    
    [self logOn_net];
}

- (BOOL)checkInput{
    if (![CheckInput isPhoneNum:self.phoneInput.text]) {
//        [self showErrorMsg:@"请输入正确的手机号"];
        LCInfoHUD(LCLocalString(@"ts_sjhyw"),1);
        return NO;
    }
    if (!self.pswInput.text.length) {
//        [self showErrorMsg:@"请输入正确的手机号"];
        LCInfoHUD(self.pswInput.placeholder,1);
        return NO;
    }
    if (self.pswInput.text.length < 8 || self.pswInput.text.length > 20) {
//        [self showErrorMsg:@"请输入正确的手机号"];
        LCInfoHUD(LCLocalString(@"mmcwts"),1);
        return NO;
    }
    if (self.needPvc && !self.pvcInput.text.length) {
        LCInfoHUD(self.pvcInput.placeholder,1);
        return NO;
    }
    return YES;
}

- (void)showErrorMsg:(NSString *)msg{
    if (msg.length) {
        [self.view endEditing:YES];
    }
    self.errMsg.text = msg;
}

- (IBAction)changeLanguage:(id)sender {
    LanguageSelectTableViewController *vc = [[LanguageSelectTableViewController alloc] init];
    [self.navigationController pushViewController:vc animated:YES];
}
- (IBAction)eyeAction:(UIButton *)sender {
    BOOL isSec = self.pswInput.secureTextEntry;
    self.pswInput.secureTextEntry = !isSec;
    
    [sender setImage:[UIImage imageNamed:isSec ? @"yj_b":@"yj_k"] forState:(UIControlStateNormal)];
}


- (void)logOn_net{
    LRLog(@"登录");
    
    NSMutableDictionary *param = @{ @"phone" : self.phoneInput.text,@"password":self.pswInput.text }.mutableCopy;
    if (self.needPvc) {
        param[@"pvc"] = self.pvcInput.text;
    }
        
    [CYXBaseRequest postWithUrl:API_passwordLoginCommit param:param resultClass:nil success:^(id res) {
        
        if ([res isEqual: RequestErrorCode]) {
            [self getLogOnConfig_net];
        }else if(res){
            LRLog(@"登录成功！");
            LCPostNotification(@"UserLogOnSuccess");
            [self dismissViewControllerAnimated:YES completion:nil];
        }
        
        CYXLog(@"%@",res)
    } failure:^(NSError *error) {
        CYXLog(@"%@",error)
    }];
}

- (void)getLogOnConfig_net{
    
    NSDictionary *param = @{ @"phone" : self.phoneInput.text };
        
    [CYXBaseRequest getWithUrl:API_passwordLoginLoad param:param resultClass:nil success:^(id res) {
        
        if ([res isEqual:RequestErrorCode]) {
            
        }else{
//            BOOL needPvc = [res[@"needPvc"] boolValue];
//            BOOL needGvc = [res[@"needGvc"] boolValue];
            self.needPvc = [res[@"needPvc"] boolValue];
            self.needGvc = [res[@"needGvc"] boolValue];
            [self configPvcView];
        }
        
        CYXLog(@"%@",res);
    } failure:^(NSError *error) {
        CYXLog(@"%@",error)
    }];
    
}

- (void)configPvcView{
    self.pvcInput.hidden = !self.needPvc;
    self.pvcBtn.hidden = !self.needPvc;
    self.pvcSepLine.hidden = !self.needPvc;
    self.errMsgTop.constant = self.needPvc ? 64 : 5;
}

#pragma mark-

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
    if (self.errMsg.text.length > 0) {
        self.errMsg.text = @"";
    }
    return YES;
}

- (BOOL)checkPhone{
    if (![CheckInput isPhoneNum:self.phoneInput.text]) {
//        [self showErrorMsg:@"请输入正确的手机号"];
        LCInfoHUD(LCLocalString(@"ts_sjhyw"),1);
        return NO;
    }
    if (!self.pswInput.text.length) {
//        [self showErrorMsg:@"请输入正确的手机号"];
        LCInfoHUD(self.pswInput.placeholder,1);
        return NO;
    }
    return YES;
}

- (void)getPvc_net:(NSString *)gvCode{
    if (![self checkPhone]) return;
    
    NSDictionary *param = @{@"phone":self.phoneInput.text,@"gvc":gvCode};
    
        [CYXBaseRequest postWithUrl:API_sendPvcForLogin param:param resultClass:nil success:^(id res) {
            if ([res isEqual: RequestErrorCode]) {
                
            }else{
                LCInfoHUD(@"驗證碼已發送", 1);
                [self.verBtn beginRun];
            }
            
            CYXLog(@"%@",res)
        } failure:^(NSError *error) {
            CYXLog(@"%@",error)
        }];
}
- (IBAction)countrySelectAction:(id)sender {
    CountryCodeSelectViewController *vc = LoadVCFormXib(CountryCodeSelectViewController);
    vc.backBlock = ^(NSDictionary * _Nonnull countryInfo) {
        self.countryCode = countryInfo[@"tel"];
        [self.codeSelectBtn setTitle:[NSString stringWithFormat:@"+%@",self.countryCode] forState:(UIControlStateNormal)];
    };
    //设置模态视图弹出样式
    vc.modalPresentationStyle = UIModalPresentationOverFullScreen;

    [self presentViewController:vc animated:YES completion:nil];
}

@end
